package com.sqx.modules.course.util;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.sqx.modules.common.dao.CommonInfoDao;
import com.sqx.modules.common.entity.CommonInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ServerUtil {
    private static int port = 22;
    /**
     * 远程服务器IP
     */
    private static String remoteHost = "222.186.57.187";
    /**
     *远程服务器账户名
     */
    private static String username = "root";
    /**
     *远程服务器密码
     */
    private static String password = "   7wang.com   ";
    /**
     * 远程服务器域名
     */
    private static String domainName = "https://v1.7wcloud.com";

    /**
     * 读取文件路径（存放的视频资源）
     */
//    private static String readPath = "/home/jz/";

    /**
     * 拼接的目标文件夹
     */
//    public static String writePath = "/7w/";




    /**
     * 获取远程服务器文件列表
     * @param fileName  服务器222.186.57.187的home文件夹下的7w/jzp文件夹下的文件夹名
     * @param map
     */
    public static List<String> getFileName(String fileName, HashMap<Long,CommonInfo> map) {
        // 获取文件名
        try {
            String username = map.get(254L).getValue();
            String remoteHost = map.get(253L).getValue();
            String password = map.get(255L).getValue();
            String readPath = map.get(251L).getValue();
            JSch jsch = new JSch();
            Session session = jsch.getSession(username, remoteHost, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            // 获取远程目录下的文件列表
            List<String> fileList = listFiles(sftpChannel, readPath+fileName);
            sftpChannel.disconnect();
            session.disconnect();
            return fileList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("短剧名输入错误或读取文件路径错误");
        }
    }

    private static List<String> listFiles(ChannelSftp sftpChannel, String remoteDir) throws Exception {
        List<String> fileList = new ArrayList<>();
        sftpChannel.cd(remoteDir);
        java.util.Vector<ChannelSftp.LsEntry> entries = sftpChannel.ls(".");
        for (ChannelSftp.LsEntry entry : entries) {
            if (!entry.getAttrs().isDir()) {
                fileList.add(entry.getFilename());
            }
        }
        return fileList;
    }

    public static String getDomainName() {
        return domainName;
    }

    public static void setDomainName(String domainName) {
        ServerUtil.domainName = domainName;
    }
}
